#include <iostream>
#include <memory>
#include "UdpServe.hpp"
#include <vector>

void Usage(char *proc)
{
  std::cout << "\n\t Usage: " << proc << "port[1024+]" << std::endl;
}

std::string Handler(const std::string &msg)
{
  std::string str = "Client say# ";
  str += msg;
  return str;
}

bool SafeCheck(const std::string &cmd)
{
  vector<std::string> cmds = {
      "rm",
      "mv",
      "cp",
      "top",
      "cd",
      "while"};

  for (auto &cd : cmds)
  {
    auto find = cmd.find(cd);
    if (find != std::string::npos)
      return false;
  }
  return true;
}

std::string ExcuteCmd(const std::string &cmd)
{

  if (!SafeCheck(cmd))
    return "Not Safe";
  FILE *pf = popen(cmd.c_str(), "r");
  if (pf == nullptr)
  {
    perror("popen");
    return "error";
  }

  std::string result;
  char buffer[4096];
  while (true)
  {
    char *ok = fgets(buffer, sizeof(buffer), pf);
    if (ok == nullptr)
      break;
    result += ok;
  }

  pclose(pf);
  return result;
}

int main(int argc, char *argv[])
{
  if (argc != 2)
  {
    Usage(argv[0]);
    exit(0);
  }
  uint16_t port = stoi(argv[1]);
  unique_ptr<UdpServe> udpsvr(new UdpServe(port));

  udpsvr->Init();

  udpsvr->Run();

  std::cout << "server started" << std::endl;

  return 0;
}